package com.demo.arch.datapulsedemo.v1_simple_direct.task;

import com.demo.arch.datapulsedemo.common.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * V1版本：简单直接实现
 * 
 * 特点：
 * - 功能完整，快速验证
 * - 步骤耦合在一起
 * - 基础重试机制
 * 
 * 局限：
 * - 步骤无法单独调整
 * - 流程固定，扩展困难
 * - 不支持断点续跑
 * 
 * @author DataPulse Team
 */
@Slf4j
@Component
public class SimpleReportTask {

  @Autowired
  private MockOrderMapper orderMapper;

  @Autowired
  private NotificationRecipientMapper recipientMapper;

  /**
   * 执行报表任务
   * 流程：查询数据 → 生成Excel → 发送通知
   */
  public TaskResult execute(String reportType) {
    log.info("========== V1报表任务开始 ==========");
    log.info("报表类型: {}", reportType);

    long startTime = System.currentTimeMillis();

    try {
      // 步骤1：查询数据
      List<OrderData> orderList = queryOrderData(reportType);

      // 步骤2：生成Excel
      String excelPath = generateExcel(orderList, reportType);

      // 步骤3：发送通知
      sendNotification(excelPath, orderList, reportType);

      long duration = System.currentTimeMillis() - startTime;
      log.info("========== V1报表任务完成，耗时: {}ms ==========", duration);

      return TaskResult.success("报表任务执行成功", excelPath);

    } catch (Exception e) {
      long duration = System.currentTimeMillis() - startTime;
      log.error("========== V1报表任务失败，耗时: {}ms ==========", duration, e);

      return TaskResult.fail("报表任务执行失败: " + e.getMessage());
    }
  }

  /**
   * 步骤1：查询订单数据
   */
  private List<OrderData> queryOrderData(String reportType) {
    log.info("--- 步骤1: 查询{}数据 ---", reportType);

    List<OrderData> orderList = orderMapper.selectByReportType(reportType);

    log.info("--- 步骤1: 完成，共查询到 {} 条记录 ---", orderList.size());

    // 打印样例数据
    if (!orderList.isEmpty()) {
      log.info("样例数据:");
      for (int i = 0; i < Math.min(3, orderList.size()); i++) {
        OrderData sample = orderList.get(i);
        log.info("  {} | {} | {} | {}",
            sample.getOrderNo(),
            sample.getCustomerName(),
            sample.getAmount(),
            sample.getStatus());
      }
    }

    return orderList;
  }

  /**
   * 步骤2：生成Excel文件
   */
  private String generateExcel(List<OrderData> orderList, String reportType) {
    log.info("--- 步骤2: 生成Excel文件 ---");

    String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
    String fileName = String.format("%s报表_%s.xlsx", reportType, timestamp);
    String filePath = "/tmp/reports/" + fileName;

    log.info("目标文件: {}", filePath);
    log.info("数据行数: {}", orderList.size());

    // 模拟Excel生成过程
    log.info("正在创建Excel工作簿...");
    log.info("正在写入表头: [订单编号, 客户名称, 订单金额, 订单时间, 订单状态]");

    // 模拟写入过程
    simulateExcelGeneration(orderList.size());

    log.info("正在保存Excel文件...");
    log.info("--- 步骤2: 完成 -> {} ---", filePath);

    return filePath;
  }

  /**
   * 步骤3：发送通知
   */
  private void sendNotification(String excelPath, List<OrderData> orderList, String reportType) {
    log.info("--- 步骤3: 发送邮件通知 ---");

    // 查询接收人
    List<NotificationRecipient> recipients = recipientMapper.selectByReportTypeAndData(reportType, orderList);

    // 构建邮件内容
    String subject = String.format("[%s] 报表生成完成通知", reportType);
    String content = buildEmailContent(reportType, excelPath, orderList.size());

    log.info("邮件主题: {}", subject);
    log.info("邮件内容:\n{}", content);

    // 发送给每个接收人
    for (NotificationRecipient recipient : recipients) {
      sendSingleEmail(recipient, subject, content);
    }

    log.info("--- 步骤3: 完成，共通知{}人 ---", recipients.size());
  }

  /**
   * 发送单个邮件
   */
  private void sendSingleEmail(NotificationRecipient recipient, String subject, String content) {
    log.info("正在发送邮件给: {} ({}) - {}",
        recipient.getName(),
        recipient.getRole(),
        recipient.getEmail());

    // 模拟邮件发送
    simulateEmailSend();

    log.info("邮件发送成功: {} ({})",
        recipient.getName(),
        recipient.getType().getDescription());
  }

  /**
   * 构建邮件内容
   */
  private String buildEmailContent(String reportType, String excelPath, int dataCount) {
    return String.format(
        """
            报表已生成完成！

            == 基本信息 ==
            报表类型: %s
            文件路径: %s
            数据条数: %d
            生成时间: %s

            请查收附件。
            """,
        reportType,
        excelPath,
        dataCount,
        LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
  }

  /**
   * 模拟Excel生成过程
   */
  private void simulateExcelGeneration(int rowCount) {
    try {
      Thread.sleep(50); // 模拟文件IO
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
    }
  }

  /**
   * 模拟邮件发送
   */
  private void simulateEmailSend() {
    try {
      Thread.sleep(30); // 模拟网络请求
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
    }
  }
}
